<?php
class p1_event extends BaseModel implements Retrievable {

	var $email;
	var $user;
	var $name;
	var $description;
	var $picture;
	var $video;
	var $video_thumb;
	var $sports;
	var $rank;
	var $type;
	
    public function p1_event($values) {
        parent::__construct($values);
    }

    public function validate() {
        $errors = Array();
        if($this->name == '') {
        	$errors[] = 'Please enter event name.';
        }
        #check duplicate name
        if($this->sports == '') {
        	$errors[] = 'Please select categories.';
        }
        if($this->email == '') {
        	$errors[] = 'Please enter email address.';
        	#TODO: check if valid email;
        }
		return (count($errors) === 0 ? true : $errors);
    }

    public static function get($id, $primaryKey='id') {
        return parent::get($id, __CLASS__, $primaryKey);
    }

    public static function getAll($searchArray=Array(), $sortArray=Array("rank", "ASC"), $limit=100) {
        return parent::getAll($searchArray, $sortArray, __CLASS__, $limit);
    }
    
    public static function getEventOfTheDay() {    		
    	$date = date('m-d-Y');
    	$file = sprintf('%s/webroot/cache/%s_event_otd.txt', DOC_ROOT, md5($date));
    	if(!file_exists($file)) {
    		$events = p1_event::getAll();
    		shuffle($events);
    		$event = $events[0];
    		$fh = fopen($file, 'w');
    		if($fh) {
    			fwrite($fh, serialize($event));
    			fclose($fh);
    		}
    	} else {
    		$event = unserialize(file_get_contents($file));
    	}
    	return $event;
    }
    
    public function exists() {
    	return ($this->id > 0);
    }
    
    public static function getNewRank() {
    	$query = "SELECT MAX(rank) as rank FROM p1_event";
    	$r = AdroitDB::$dbase->fetchValue($query);
    	return $r ? ($r+1) : 1;
    }
    
    public function updateFrom($data) {
    	if(is_array($data)) {
    		foreach($data as $k=>$v) {
    			$this->$k = $v;
    		}
    	}
    }
    
    public static function search($keywords) {
    	$keywords = addslashes($keywords);
    	$query = "SELECT e.*, MATCH(e.name, e.description) AGAINST('{$keywords}' IN BOOLEAN MODE) as relevance 
					FROM p1_event e 
					WHERE  
					MATCH(e.name, e.description) AGAINST('{$keywords}' IN BOOLEAN MODE) 
					HAVING relevance > 0.0 ORDER BY relevance DESC";
    	return BaseModel::getByQuery($query, __CLASS__);
    }
}
?>